package cn.hdu.liang.core.bean;

import org.codehaus.jackson.annotate.JsonIgnore;

import java.util.ArrayList;
import java.util.List;

public class BuyCart {
    //购物项集合
    private List<BuyItem> items = new ArrayList<>();
    private Integer productId;

    //添加到购物车
    public void addItem(BuyItem item) {
        if(items.contains(item)) {
            for(BuyItem it : items) {
                if(it.equals(item)) {
                    int result = it.getAmount() + item.getAmount();
                    if(it.getSku().getSkuUpperLimit() >= result) {
                        it.setAmount(result);
                    } else {
                        it.setAmount(it.getSku().getSkuUpperLimit());
                    }
                }
            }
        } else {
            items.add(item);
        }
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public List<BuyItem> getItems() {
        return items;
    }

    //商品数量
    @JsonIgnore
    public Integer getProductAmount() {
        return items.stream().mapToInt(BuyItem::getAmount).sum();
    }

    //商品金额
    @JsonIgnore
    public Double getProductPrice() {
        return items.stream().mapToDouble(item -> item.getSku().getSkuPrice() * item.getAmount()).sum();
    }

    //运费
    @JsonIgnore
    public Double getFee() {
        Double result = 0.0;
        if(getProductPrice() <= 39) {
            result = 10.0;
        }
        return result;
    }

    //应付金额
    @JsonIgnore
    public Double getTotalPrice() {
        return getFee() + getProductPrice();
    }

    //清空购物车
    public void clearCart() {
        items.clear();
    }

    //删除一个项
    public void deleteItem(BuyItem item) {
        items.remove(item);
    }

}
